'''
Created on 09/04/2009

@author: eh01
'''
from yarra import xmlconstants
from yarra.datastore import dsconstants, dsofactory
from yarra.datastore.dsstub import DSStub
from yarra.event import eventconstants
from yarra.event.event import Event
from yarra.event.eventhandler import BaseEventHandler
from yarra.event.eventmanager import EventManager
from yarra.logindecorator import loginRequired
import re
import time



class HTTPRequestGETNodeMessagesHandler(BaseEventHandler):

    @loginRequired
    def do(self, data):
        dso = data
        http_request = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_HTTP_REQUEST).get_literal()
        lock = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_LOCK).get_literal()                    
        event_type = eventconstants.HTTP_RESPONSE_EVENT_TYPE
        
        ds_stub = DSStub()
                
        matches = re.match('/node/(\d+)(\?wait=(\w+))?$', http_request.path)
        
        # log that the node has made a connection to the hub
        node_id = int(matches.group(1))
        ds_stub.put_node(node_id)
        
        messages = None
        wait = matches.group(3)
        
        # if wait = True, then wait for incoming messages for approx 30 seconds
        if wait:
            for i in range(300):
#                curr_thread = threading.currentThread()
#                print curr_thread.getName() + ': Check ' + str(i)
                messages = ds_stub.get_messages(node_id)
                if messages:
                    break
                else:
                    time.sleep(0.1)
        else:    
            messages = ds_stub.get_messages(node_id)
        
        response_body = xmlconstants.XML_VERSION_TAG + \
                        xmlconstants.MESSAGES_TAG_OPENING
        
        if messages:
            for message_id in messages.keys():
                response_body += xmlconstants.ID_TAG_OPENING + \
                                    str(message_id) + \
                                    xmlconstants.ID_TAG_CLOSING
                                
        response_body += xmlconstants.MESSAGES_TAG_CLOSING

        # create new dso        
        new_dso = dsofactory.create_dso_for_im_http_response_handler(200, 
                                                               xmlconstants.XML_CONTENT_TYPE, 
                                                               response_body, 
                                                               http_request, 
                                                               lock)
        event = Event(event_type, new_dso)
        EventManager().add_event(event)        
                